<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\ScoreRuleController;
use App\Models\GoodsOrder;
use App\Models\OweOrder;
use App\Models\OweOrderRecord;
use App\Models\BookHomePurchaseSet;
use App\Validate\OweProcessValidate;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 欠费模块
 * Class PayInfo
 * @package app\port\controlle
 */
class OweProcessController extends CommonController
{
    public $validate = null;


    public function __construct()
    {
        parent::__construct();
        $this->validate = new OweProcessValidate();
    }

    /**
     * 欠费列表
     * @param $authorrization ：用户 token  可选
     *    //模拟数据后期删除
            // $res['content']["list"] = [
            //     [
            //         "finAccountId" => 310827,
            //         "money" => 9900,
            //         "moneyYuan" => "99.00",
            //         "costType" => "Depi",
            //         "costTypeNote" => "专项手动欠款",
            //         "updateDate" => "2021-01-04",
            //         "updateTime" => "15:21:28",
            //         "adminName" => "wh",
            //         "notes" => "首次芯片损坏",
            //         "finEventId" => 382704
            //     ],
            //     [
            //         "finAccountId" => 111,
            //         "money" => 9900,
            //         "moneyYuan" => "99.00",
            //         "costType" => "Depi",
            //         "costTypeNote" => "图书超期滞纳金",
            //         "updateDate" => "2021-01-04",
            //         "updateTime" => "15:21:28",
            //         "adminName" => "wh",
            //         "notes" => "首次芯片损坏",
            //         "finEventId" => 382704
            //     ]
            // ];
     */
    public function oweList()
    {
        $account = request()->user_info['account'];
        $user_id = request()->user_info['id'];
        $account_id = request()->user_info['account_id'];

        $libApi = $this->getLibApiObj();
        $res = $libApi->getReaderArrearsListPageInfo($account, 1, 100);

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(23);

        if ($res['code'] == 200 && $res['content']['list']) {
            //获取兑换比例
            $BookHomePurchaseSetModelObj = new BookHomePurchaseSet();
            $subscription_ratio = $BookHomePurchaseSetModelObj->where('type', 15)->first(); //查询兑换比例
            //获取总金额
            $price = 0; //单位分
            foreach ($res['content']['list'] as $key => $val) {
                $price += $val['money'];
            }
            $res['content']['total_money'] = sprintf("%.2f", $price / 100);
            $scoreRuleModel = new ScoreRuleController();
            $res['content']['user_score'] = $scoreRuleModel->getUserScore($user_id, $account_id);
            $res['content']['subscription_ratio'] = !empty($subscription_ratio['number']) ? $subscription_ratio['number'] : null;
            return $this->returnApi(200, '获取成功', true, $res['content']);
        }

        // $res['content']["list"] = [
        //     [
        //         "finAccountId" => 310827,
        //         "money" => 9900,
        //         "moneyYuan" => "99.00",
        //         "costType" => "Depi",
        //         "costTypeNote" => "专项手动欠款",
        //         "updateDate" => "2021-01-04",
        //         "updateTime" => "15:21:28",
        //         "adminName" => "wh",
        //         "notes" => "首次芯片损坏",
        //         "finEventId" => 382704
        //     ],
        //     [
        //         "finAccountId" => 111,
        //         "money" => 9900,
        //         "moneyYuan" => "99.00",
        //         "costType" => "Depi",
        //         "costTypeNote" => "图书超期滞纳金",
        //         "updateDate" => "2021-01-04",
        //         "updateTime" => "15:21:28",
        //         "adminName" => "wh",
        //         "notes" => "首次芯片损坏",
        //         "finEventId" => 382704
        //     ]
        // ];

        // return $this->returnApi(200, '获取成功', true, $res['content']);

        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 欠费支付 生成预支付订单
     * @param $authorrization 用户 token    例：Bearer 1 必选
     * @param $fin_account_id 欠款记录号 多个逗号拼接
     * @param $way 缴费方式   1 微信 2 积分 
     */
    public function owePay()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('owe_pay')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $fin_account_id = $this->request->input('fin_account_id');
        $way = $this->request->input('way');
        $user_id = request()->user_info['id'];;
        $account = request()->user_info['account'];
        $account_id = request()->user_info['account_id'];;

        $oweOrderModelObj = new OweOrder();
        $oweOrderRecordModelObj = new OweOrderRecord();

        //查询系统，获取金额
        $libApi = $this->getLibApiObj();
        $pay_list = $libApi->getReaderArrearsListPageInfo($account, 1, 100);
        if ($pay_list['code'] != 200) {
            return $this->returnApi(202, '获取失败');
        }

        DB::beginTransaction();
        try {
            $fin_account_id_arr = array_filter(array_unique(explode(',', $fin_account_id)));

            //添加订单
            $oweOrderModelObj->order_number = get_order_id(); //获取订单号
            $oweOrderModelObj->user_id = $user_id;
            $oweOrderModelObj->account_id = $account_id;
            $oweOrderModelObj->payment = $way;
            $oweOrderModelObj->save();

            //计算积分所需金额
            $fin_account_list = [];
            $price = 0; //单位分
            $i = 0;

            foreach ($pay_list['content']['list'] as $key => $val) {
                if (in_array($val['finAccountId'], $fin_account_id_arr)) {
                    $fin_account_list[$i]['order_id'] = $oweOrderModelObj->id;
                    $fin_account_list[$i]['fin_account_id'] = $val['finAccountId'];
                    $fin_account_list[$i]['price'] = $val['moneyYuan'];
                    $fin_account_list[$i]['price_fen'] = $val['money'];
                    $fin_account_list[$i]['cost_type'] = $val['costType'];
                    $fin_account_list[$i]['cost_type_note'] = $val['costTypeNote'];
                    $fin_account_list[$i]['update_time'] = $val['updateDate'] . ' ' . $val['updateTime'];
                    $fin_account_list[$i]['intro'] = $val['notes'];
                    $fin_account_list[$i]['fin_event_id'] = $val['finEventId'];
                    $fin_account_list[$i]['create_time'] = date('Y-m-d H:i:s');
                    $i++;
                    $price += $val['money'];
                }
            }
            if (empty($fin_account_list)) {
                throw new Exception('获取订单失败');
            }
            $oweOrderRecordModelObj->insert($fin_account_list);

            if ($way == 2) {
                $bookHomePurchaseSetModelObj = new BookHomePurchaseSet();
                $subscription_ratio = $bookHomePurchaseSetModelObj->where('type', 15)->first(); //查询兑换比例

                if (empty($subscription_ratio) || empty($subscription_ratio['number']) || $subscription_ratio['number'] < 1) {
                    throw new Exception('积分兑换比例获取失败，请联系管理员处理');
                }
                $score = $price * $subscription_ratio['number']; //所需积分
                //查询用户积分，然后修改用户积分
                $scoreRuleObj = new ScoreRuleController();
                $user_score = $scoreRuleObj->getUserScore($user_id, $account_id); //获取用户积分

                if (is_string($user_score)) {
                    throw new Exception($user_score); //正常，不操作积分
                }
                if ($score > $user_score) {
                    throw new Exception('积分不足，缴纳失败');
                }

                $price_yuan = sprintf("%.2f", $price / 100);
                $system_id = $this->systemAdd('欠款缴纳积分抵扣成功', $user_id, $account_id, 22, 0, '使用【' . $score . '】积分，抵扣了“' . $price_yuan . '”欠款');
                $scoreRuleObj->scoreGoodChange($score, $user_id, $account_id, '欠款缴纳积分抵扣成功', '使用【' . $score . '】积分，抵扣了“' . $price_yuan . '”欠款', $system_id, 999); //添加积分消息

                $oweOrderModelObj->score = $score;
                $oweOrderModelObj->price = $price_yuan;
                $oweOrderModelObj->price_fen = $price;
                $oweOrderModelObj->payment = 2;
                $oweOrderModelObj->is_pay = 2; //直接变成已支付
                $oweOrderModelObj->save();

                //处理真实数据
                $res = $libApi->payArrears($account, $fin_account_id_arr, 2); //修改真实数据
                if ($res['code'] !== 200) {
                    throw new Exception($res['msg']);
                }
            } else {
                $oweOrderModelObj->price = sprintf("%.2f", $price / 100);
                $oweOrderModelObj->price_fen = $price;
                $oweOrderModelObj->payment = 1;
                $oweOrderModelObj->is_pay = 1; //未支付
                $oweOrderModelObj->save();
            }

            DB::commit();
            return $this->returnApi(200, '缴纳成功', true, [
                'order_id' => $oweOrderModelObj->id,
                'order_number' => $oweOrderModelObj->order_number,
                'create_time' => $oweOrderModelObj->create_time,
                'price' => sprintf("%.2f", $price),
                'postage_budget' => $way == 2 ? true : false  //true 表示已支付，不需要支付，false 表示未支付需要支付
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
